package org.webgene.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

public class URLChecker {
	private Logger logger = Logger.getLogger(URLChecker.class);
	private String url;
	public boolean isValidURL(String url) {
		if (url == null) return false;
		this.url = url;
		logger.info(String.format("isValidURL Input url: %s", url));
		return validationCheck();
	}

	private boolean validationCheck(){
		logger.info(String.format("validationCheck url: %s", url));
		String pattern = "[0-9A-Za-z]+(\\.\\w+)+";
		String sourceUrl = removeProtocol();
		return isMatch(sourceUrl, pattern);
	}
	
	private String removeProtocol(){
		String removeString = url.replaceFirst("(http://|https://)", "");
		logger.info(String.format("removeProtocol: %s", removeString));
		return removeString;
	}
	
    private boolean isMatch(String url, String regex) {
        logger.info(String.format("url: %s, regex: %s", url, regex));
    	try {
            Pattern patt = Pattern.compile(regex);
            Matcher matcher = patt.matcher(url);
            return matcher.matches();
        } catch (RuntimeException e) {
        	return false;
        }
    }  
}
